package com.liusand.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liusand.mapper.PatientMapper;
import com.liusand.mapper.UsersAccountMapper;
import com.liusand.model.dto.RegisterDto;
import com.liusand.model.pojo.Patient;
import com.liusand.model.pojo.Users;
import com.liusand.mapper.UsersMapper;
import com.liusand.model.pojo.UsersAccount;
import com.liusand.model.vo.OpenIdVo;
import com.liusand.model.vo.RegisterVo;
import com.liusand.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 小程序用户 服务实现类
 * </p>
 *
 * @author liusand
 * @since 2023-01-29
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UsersAccountMapper usersAccountMapper;

    @Autowired
    private PatientMapper patientMapper;

    @Override
    public OpenIdVo openId(String code) {
        if(StringUtils.isEmpty(code)){
            throw new RuntimeException("openId传参异常");
        }
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:9090/sns/jscode2session";
        url += "?appid=wxe6f0c12631e361d0";
        url += "&secret=6cb71ccff4a8bb85c153ad6ec996855c";
        url += "&js_code=" + code;
        url += "&grant_type=authorization_code";

        Map map = restTemplate.getForObject(url, Map.class);
        if(map == null){
            throw new RuntimeException("微信服务请求异常");
        }
        if(map.get("errcode") != null && (Integer) map.get("errcode") != 0){
            throw new RuntimeException("微信服务请求异常,错误码:" + map.get("errcode") + ",错误信息:" + map.get("errmsg"));
        }
        OpenIdVo openIdVo = new OpenIdVo();
        openIdVo.setOpenId((String) map.get("openid"));
        return openIdVo;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public RegisterVo register(RegisterDto registerDto) {
        if(registerDto == null){
            throw new RuntimeException("register传参异常");
        }
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Users::getOpenId, registerDto.getOpenId());
        wrapper.eq(Users::getPhone, registerDto.getPhone());
        Users users = usersMapper.selectOne(wrapper);
        Integer userId;
        String openId;
        if(users == null){
            Users newUser = new Users();
            BeanUtils.copyProperties(registerDto, newUser);
            newUser.setNickname(registerDto.getNickName());
            newUser.setAvatar(registerDto.getAvatarUrl());
            int usersInsertResult = usersMapper.insert(newUser);
            if(usersInsertResult != 1){
                throw new RuntimeException("插入异常");
            }

            UsersAccount newUsersAccount = new UsersAccount();
            newUsersAccount.setUserId(newUser.getId());
            newUsersAccount.setBalance(0);
            int accountInsertResult = usersAccountMapper.insert(newUsersAccount);
            if(accountInsertResult != 1){
                throw new RuntimeException("插入异常");
            }

            Patient newPatient = new Patient();
            newPatient.setUserId(newUser.getId());
            newPatient.setName(newUser.getNickname());
            newPatient.setTags("本人");
            newPatient.setCardNumber("");
            newPatient.setCardType(0);
            newPatient.setPhone(newUser.getPhone());
            newPatient.setAddress(newUser.getCountry() + newUser.getProvince() + "省" + newUser.getCity() + "市");
            newPatient.setIsDefault(1);
            int patientInsertResult = patientMapper.insert(newPatient);
            if(patientInsertResult != 1){
                throw new RuntimeException("插入异常");
            }
            userId = newUser.getId();
            openId = newUser.getOpenId();
        }else {
            userId = users.getId();
            openId = users.getOpenId();
        }

        Map<String, Object> map = new HashMap<>();
        map.put("id", String.valueOf(userId));
        map.put("openId", openId);
        String token = JWTUtil.createToken(map, "ABCDEFG".getBytes());
        RegisterVo registerVo = new RegisterVo();
        registerVo.setToken(token);
        return registerVo;
    }
}
